package com.ymatou.iapi.liveinfo.testcase;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.liveinfo.parameter.ListInProgressActivitiesByIdsBean;
import com.ymatou.iapi.liveinfo.service.ListInProgressActivitiesByIdsCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.*;
import com.ymt.utils.tag.*;
import com.ymttest.business.service.LiveCallService;
import com.ymttest.database.mongo.jproduct.LiveProductsWapper;
import com.ymttest.database.mongo.jproduct.LivesWapper;
import com.ymttest.database.mongo.jproduct.ProductsWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
/**
*根据多个直播id获取直播列表
*FreeMaker Template自动生成代码
*/
@TestSuite
public class Ts_ListInProgressActivitiesByIds{
	private static int sellerId = Integer.parseInt(EnvSetup.getData("productsellerid"));
	private static String sellerName = EnvSetup.getData("productsellername");
	private static int sellerId2 = Integer.parseInt(EnvSetup.getData("productsellerid2"));
	private static String sellerName2 = EnvSetup.getData("productsellername2");
	private static ListInProgressActivitiesByIdsBean bean;
	private static ListInProgressActivitiesByIdsCall call;
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("根据多个直播id获取直播列表");
	}

	@Before
	public void caseUp() {
		bean=new ListInProgressActivitiesByIdsBean();
		call=new ListInProgressActivitiesByIdsCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(call.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_ListInProgressActivitiesByIds_001() {
		Logger.start(true,"根据多个直播id获取直播列表-直播Id长度为1-商品数量为1");
		try {
			//根据条件查询 直播Id长度为1，却商品数量为1 的直播
			List<Integer> ActivityIds=new ArrayList();
			Integer lid=LiveCallService.createLivesInProcessAndInFuture(sellerId,sellerName,1,1).get(0);
			LivesWapper wapper = new LivesWapper();
			String cover="http://m.ymatou.com/"+TestDataManager.getRandomUUID().toString();
			wapper.updateCover(lid.toString(), cover);
		    ActivityIds.add(lid);
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,1);
			Thread.sleep(1000); 
			
			bean.setActivityIds(ActivityIds);
			bean.setProductNum(1);
			call.setData(bean);
			call.callService();			
			GetVerify(ActivityIds,bean.getProductNum());
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_ListInProgressActivitiesByIds_002() {
		Logger.start(true,"根据多个直播id获取直播列表-直播Id长度为2-商品数量为1");
		try {
			List<Integer> ActivityIds=new ArrayList();
			//创建第一个直播
			int lid=LiveCallService.createLivesInProcessAndInFuture(sellerId,sellerName,1,1).get(0);
		    ActivityIds.add(lid);
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,1);
			//创建第二个直播
			int lid2=LiveCallService.createLivesInProcessAndInFuture(sellerId2,sellerName2,1,1).get(0);
		    ActivityIds.add(lid2);
			LiveCallService.CreateLivesProductByLivesId(sellerId2,sellerName2,lid2,1);
			Thread.sleep(3000); 
			
			bean.setActivityIds(ActivityIds);
			bean.setProductNum(1);
			call.setData(bean);
			call.callService();			
			GetVerify(ActivityIds,bean.getProductNum());		
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_ListInProgressActivitiesByIds_003() {
		Logger.start(true,"根据多个直播id获取直播列表-直播Id长度为2-商品数量为2");
		try {		
			List<Integer> ActivityIds=new ArrayList();
			//创建第一个直播
			int lid=LiveCallService.createLivesInProcessAndInFuture(sellerId,sellerName,1,1).get(0);
		    ActivityIds.add(lid);
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,2);
			//创建第二个直播
			int lid2=LiveCallService.createLivesInProcessAndInFuture(sellerId2,sellerName2,1,1).get(0);
		    ActivityIds.add(lid2);
			LiveCallService.CreateLivesProductByLivesId(sellerId2,sellerName2,lid2,2);
			Thread.sleep(6000); 
			
			bean.setActivityIds(ActivityIds);
			bean.setProductNum(2);
			call.setData(bean);
			call.callService();			
			GetVerify(ActivityIds,bean.getProductNum());
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_ListInProgressActivitiesByIds_004() {
		Logger.start(true,"根据多个直播id获取直播列表-直播Id长度为1-商品数量为2");
		try {
			List<Integer> ActivityIds=new ArrayList();
			//创建第一个直播
			int lid=LiveCallService.createLivesInProcessAndInFuture(sellerId,sellerName,1,1).get(0);
		    ActivityIds.add(lid);
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,2);
			Thread.sleep(10000); 
			
			bean.setActivityIds(ActivityIds);
			bean.setProductNum(2);
			call.setData(bean);
			call.callService();			
			GetVerify(ActivityIds,bean.getProductNum());		
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_ListInProgressActivitiesByIds_005() {
		Logger.start(true,"根据多个直播id获取直播列表-直播Id长度为1-商品数量为2(其中商品总数量是3)");
		try {
			List<Integer> ActivityIds=new ArrayList();
		   //创建第一个直播
			int lid=LiveCallService.createLivesInProcessAndInFuture(sellerId,sellerName,1,1).get(0);
		   // ActivityIds.add(159496);
			ActivityIds.add(lid);
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,4);
			Thread.sleep(1000); 
			
			bean.setActivityIds(ActivityIds);
 		    bean.setActivityIds(ActivityIds);
			bean.setProductNum(2);
			call.setData(bean);
			call.callService();			
			GetVerify(ActivityIds,bean.getProductNum());		
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_ListInProgressActivitiesByIds_006() {
		Logger.start(true,"根据多个直播id获取直播列表-直播Id为null-商品数量为2(其中商品总数量是3)");
		try {
			List<Integer> ActivityIds=new ArrayList();
		   //创建第一个直播
			//int lid=LiveCallService.createLivesInProcessAndInFuture(sellerId,sellerName,1,1).get(0);
		   // ActivityIds.add(159496);
			ActivityIds.add(null);
//			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,4);
//			Thread.sleep(1000); 
			
 		    bean.setActivityIds(ActivityIds);
			bean.setProductNum(2);
			call.setData(bean);
			call.callService();			
			Logger.verifyEquals(200, call.getCode(), "判断code是否为200");
			Logger.verifyEquals("操作成功",call.getMsg(), "判断Msg返回操作成功");
			Logger.verifyEquals(0,call.getBCode(), "判断操作成功时 业务代码是否0");
			Logger.verifyNotNull(call.getServerTime(), "判断服务器时间是否为空");
			Logger.verifyEquals(0, call.getData().getInt("ActivityCount"), "验证ActivityCount为0");	
			Logger.verifyEquals("[]",call.GetActivities().toString(), "判断服务器时间是否为空");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	private void GetVerify(List<Integer> livelst,int productNum) throws Exception
	{
		if(livelst.size()>0 )
		{
		LivesWapper livesWapper=new LivesWapper();
		for(int i=0;i<livelst.size();i++)
        {
			int count=i+1;
            Map<String,Object> lst=livesWapper.getLivesBylid(livelst.get(i));
			Logger.verifyEquals(200, call.getCode(), "判断code是否为200");
			Logger.verifyEquals("操作成功",call.getMsg(), "判断Msg返回操作成功");
			Logger.verifyEquals(0,call.getBCode(), "判断操作成功时 业务代码是否0");
			Logger.verifyNotNull(call.getServerTime(), "判断服务器时间是否为空");
			
			Logger.verifyEquals(livelst.size(), call.getData().getInt("ActivityCount"), "验证第"+count+"个直播ActivityCount是否与mongodb一致");
			Logger.verifyEquals(lst.get("title"), call.GetActivities().getJSONObject(i).getString("Title"), "验证第"+count+"个直播title是否与mongodb一致");
			Logger.verifyEquals(lst.get("vcover"), call.GetActivities().getJSONObject(i).getString("VideoCover"), "验证第"+count+"个直播VideoCover是否与mongodb一致");
			Logger.verifyEquals(lst.get("vurl"), call.GetActivities().getJSONObject(i).getString("VideoUrl"), "验证第"+count+"个直播VideoUrl是否与mongodb一致");
			Logger.verifyEquals(lst.get("action").toString(), call.GetActivities().getJSONObject(i).getString("Action").toString(), "验证第"+count+"个直播Action是否与mongodb一致");
			Logger.verifyEquals(lst.get("lid").toString(), call.GetActivities().getJSONObject(i).getString("ActivityId").toString(), "验证第"+count+"个直播ActivityId是否与mongodb一致");
			Logger.verifyEquals(lst.get("name"), call.GetActivities().getJSONObject(i).getString("ActivityName"), "验证第"+count+"个直播ActivityName是否与mongodb一致");
			Logger.verifyEquals(lst.get("pic"), call.GetActivities().getJSONObject(i).getString("ActivityPicture"), "验证第"+count+"个直播ActivityPicture是否与mongodb一致");
			Logger.verifyEquals(lst.get("cover")==null?"null":lst.get("cover").toString(), call.GetActivities().getJSONObject(i).getString("LiveCover"), "验证第"+count+"个直播VideoCover是否与mongodb一致");
			
			Logger.verifyEquals((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("add")).toString(), call.GetActivities().getJSONObject(i).getString("AddTime").toString(), "验证第"+count+"个直播AddTime是否与mongodb一致");
			Logger.verifyEquals(lst.get("country"), call.GetActivities().getJSONObject(i).getString("Country"), "验证第"+count+"个直播Country是否与mongodb一致");
			Logger.verifyEquals((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("end")), call.GetActivities().getJSONObject(i).getString("EndTime"), "验证第"+count+"个直播EndTime是否与mongodb一致");
			Logger.verifyEquals(lst.get("sid").toString(), call.GetActivities().getJSONObject(i).getString("SellerId").toString(), "验证第"+count+"个直播SellerId是否与mongodb一致");
			Logger.verifyEquals(lst.get("addr"), call.GetActivities().getJSONObject(i).getString("ShopAddress"), "验证第"+count+"个直播ShopAddress是否与mongodb一致");
			Logger.verifyEquals((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("start")), call.GetActivities().getJSONObject(i).getString("StartTime"), "验证第"+count+"个直播StartTime是否与mongodb一致");
			
			Logger.verifyEquals(lst.get("confirm").toString(), call.GetActivities().getJSONObject(i).getString("AppConfirmed"), "验证第"+count+"个直播AppConfirmed是否与mongodb一致");
			Logger.verifyEquals(lst.get("content"), call.GetActivities().getJSONObject(i).getString("ActivityInfo"), "验证第"+count+"个直播ActivityInfo是否与mongodb一致");
//			Logger.verifyEquals(lst.get("cover"), lst.get("LiveCover"), "验证直播LiveCover是否与mongodb一致");
			
			String start=(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("start"));
			String end=(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(lst.get("end"));
			
			Logger.verifyEquals(GetActivityStatusText(lst,start,end).split(",")[0], call.GetActivities().getJSONObject(i).getString("ActivityStatusText"), "验证第"+count+"个直播ActivityStatusText是否与mongodb一致");
			Logger.verifyEquals(GetActivityStatusText(lst,start,end).split(",")[1], call.GetActivities().getJSONObject(i).getString("ActivityState"), "验证第"+count+"个直播ActivityState是否与mongodb一致");
			VerifyerifyProduct((int)lst.get("lid"),productNum,i);
		 }
		
		}
	}
	private void VerifyerifyProduct(int livesId,int productNum,int activeCount) throws Exception
	{
	  LiveProductsWapper liveProductsWapper=new LiveProductsWapper();
	  ProductsWapper productsWapper=new ProductsWapper();
	  String spid="";
	  JSONArray ProductList=call.GetActivities().getJSONObject(activeCount).getJSONArray("ProductList");
	   ArrayList<Map> lst=liveProductsWapper.getLiveProductsBylid(livesId,productNum,"{sort:1}");
	  for(int i=0;i<lst.size();i++) 
	  {
		JSONObject jo = new JSONObject(lst.get(i));
		spid=jo.getString("spid");
		
		if(spid!="")
		{
		 ArrayList<Map> plst=productsWapper.getProductsBySpid(spid,productNum);
		 if(plst.size()>0 )
		 {
			for(int j=0;j<plst.size();j++)
			{
			JSONObject pjo = new JSONObject(plst.get(j));
			Logger.verifyEquals(pjo.getBoolean("ispsp"),ProductList.getJSONObject(i).getBoolean("IsPsp"), "验证直播商品IsPsp是否与mongodb一致");
			Logger.verifyEquals(pjo.getString("spid"), ProductList.getJSONObject(i).getString("ProductId"), "验证直播商品ProductId是否与mongodb一致");
			Logger.verifyEquals(pjo.getString("pics").replace('[', ' ').toString().replace(']', ' ').replace('"', ' ').trim(), ProductList.getJSONObject(i).getString("PicUrl"), "验证直播商品PicUrl是否与mongodb一致");
			//获取最低价格
			String[] mlst=pjo.getString("minp").split(",");
			
			List<BigDecimal> newmlst = new ArrayList();
			for(int k=0;k<mlst.length;k++)
			{
				 DecimalFormat df = new DecimalFormat("#.0");
				 BigDecimal m=new BigDecimal(mlst[k]);
				if(m.compareTo(new BigDecimal("0.0"))!=0)
					newmlst.add(m);
			}
			Collections.sort(newmlst);
			Logger.verifyEquals(newmlst.get(0).toString(), ProductList.getJSONObject(i).getString("Price"), "验证直播商品Price是否与mongodb一致");
			Logger.verifyEquals(newmlst.get(0).toString(), ProductList.getJSONObject(i).getString("VipPrice"), "验证直播商品VipPrice是否与mongodb一致");
			Logger.verifyEquals(newmlst.get(0).toString(), ProductList.getJSONObject(i).getString("NewGuestPrice"), "验证直播商品NewGuestPrice是否与mongodb一致");
			//LiveProducts 上的 status
			ArrayList<String> lplst=liveProductsWapper.getLivesProductsBySpid(spid);
			if(lplst.size()>0)
			{
				Logger.verifyEquals(new JSONObject(lplst.get(0)).getString("status"), ProductList.getJSONObject(j).getString("SellStatus"), "验证直播商品SellStatus是否与mongodb一致");
			}
		   }
    	}
		 else if(plst.size()>0 && (ProductList!=null || ProductList.length()>0))
		 {
			 Logger.verifyNotNull(null, "验证直播商品集合GetProductList是否与mongodb一致");
		 }
		}
	  }
	}
	/**
	 * 获取直播状态文字和状态key
	 * @param lst
	 * @return
	 * @throws ParseException
	 * @throws JSONException
	 */
	private String GetActivityStatusText(Map<String,Object> lst,String start1,String end1) throws ParseException, JSONException
	{
		String text="";
		Date currentTime = new Date();

		if((int)lst.get("action")==1 )
		{
			Calendar calendar  =  new   GregorianCalendar(); 
			calendar.setTime(currentTime); 
			calendar.add(calendar.HOUR,1);
			Date newCurrentTime=calendar.getTime();
			
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date start=format.parse(start1);
			Date end=format.parse(end1);
			if((boolean)lst.get("confirm")==true && ((currentTime.after(start)|| currentTime==start)&& (end.after(currentTime)|| currentTime==end)))
				text="直播中,0";
			else if((boolean)lst.get("confirm")==true && start.after(currentTime) && end.after(start))
				text="即将开始,-1";
			else if((boolean)lst.get("confirm")==false && end.after(newCurrentTime))
				text="未生效,2";
			else
				text="已结束,其他";
		}
		return text;
	}
}